package com.weizhi.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weizhi.server.dto.CategoryDto;
import com.weizhi.server.entity.Category;
import com.weizhi.server.mapper.CategoryMapper;
import com.weizhi.server.service.CategoryService;
import com.weizhi.server.util.PropertyCopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    private final static Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public List<CategoryDto> all() {
        List<Category> categoryList = categoryMapper.all();
        List<CategoryDto> categoryDtoList = PropertyCopyUtil.copyList(categoryList, CategoryDto.class);
        //分级处理
        List<CategoryDto> list = new ArrayList<>();
        for (CategoryDto parent: categoryDtoList) {
            if(parent.getParentId() == 0){//一级分类
                list.add(parent);
                parent.setChildrenList(new ArrayList<>());
                for(CategoryDto child: categoryDtoList){
                    if(child.getParentId() == parent.getId()){
                        parent.getChildrenList().add(child);
                    }
                }
            }
        }
        return list;
    }

    @Override
    public void save(CategoryDto categoryDto) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDto, category);
        if(category.getId() == null){
            if(category.getParentId() == null) category.setParentId(0L);
            categoryMapper.insertSelective(category);
        }else{
            categoryMapper.updateByPrimaryKey(category);
        }

    }

    @Override
    @Transactional
    public void delete(Long id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        if(category.getParentId() == 0) {
            categoryMapper.deleteByParentId(category.getParentId());
        }
        categoryMapper.deleteByPrimaryKey(id);
    }
}
